
package com.beans.annotation;

import com.beans.factory.BeanDefinition;
import com.context.annotation.AnnotationConfigUtils;
import com.context.annotation.Scope;
import com.context.annotation.ScopeMetadata;
import com.context.annotation.ScopedProxyMode;
import com.core.annotation.AnnotationAttributes;

import java.lang.annotation.Annotation;


public class AnnotationScopeMetadataResolver implements ScopeMetadataResolver {

	private final ScopedProxyMode defaultProxyMode;

	protected Class<? extends Annotation> scopeAnnotationType = Scope.class;

	public AnnotationScopeMetadataResolver() {
		this.defaultProxyMode = ScopedProxyMode.NO;
	}

	public AnnotationScopeMetadataResolver(ScopedProxyMode defaultProxyMode) {
		this.defaultProxyMode = defaultProxyMode;
	}

	@Override
	public ScopeMetadata resolveScopeMetadata(BeanDefinition definition) {
		ScopeMetadata metadata = new ScopeMetadata();
		if (definition instanceof AnnotatedBeanDefinition) {
			AnnotatedBeanDefinition annDef = (AnnotatedBeanDefinition) definition;
			AnnotationAttributes attributes = AnnotationConfigUtils.attributesFor(
					annDef.getMetadata(), this.scopeAnnotationType);
			if (attributes != null) {
				metadata.setScopeName(attributes.getString("value"));
				ScopedProxyMode proxyMode = attributes.getEnum("proxyMode");
				if (proxyMode == ScopedProxyMode.DEFAULT) {
					proxyMode = this.defaultProxyMode;
				}
				metadata.setScopedProxyMode(proxyMode);
			}
		}
		return metadata;
	}

}
